<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">    <i class="el-icon-location-information"></i>    首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <div style="margin-top: 15px;">
                <el-row v-bind:gutter = '0'>
                    <el-col :span="8">
                        <el-input placeholder="请输入内容" class="input-with-select" v-model="queryinfo.query" clearable v-on:clear="getuserlist()">
                            <el-button slot="append" icon="el-icon-search" v-on:click="getuserlist()"></el-button>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="success" plain @click="adddialogVisible = true">添加用户</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-table v-bind:data= "userlist" border :stripe="true" :highlight-current-row="true">
                <el-table-column type= 'index' ></el-table-column>
                <el-table-column label = "姓名" prop= 'username'></el-table-column>
                <el-table-column label = "邮箱" prop= 'email'></el-table-column>
                <el-table-column label = "电话" prop= 'mobile'></el-table-column>
                <el-table-column label = "角色" prop= 'role_name'></el-table-column>
                <el-table-column label = "权限" prop= 'mg_state'>
                    <template slot-scope="scope">
                        <el-switch
                        style="display: block"
                        v-model="scope.row.mg_state"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-text="开启"
                        inactive-text="冻结" v-on:change= "changestatus(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label = "操作" >
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size='mini' v-on:click="edituser(scope.row)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size='mini' v-on:click= "deleteuser(scope.row)"></el-button>
                        <el-button type="warning" icon="el-icon-setting" size='mini'></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-pagination background layout="total,prev, pager, next" :total="total" v-bind:current-page="queryinfo.pagenum" v-bind:page-size="queryinfo.pagesize" v-on:current-change='handlecurrentchange'>
        </el-pagination>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" v-on:close="diaclosed" :visible.sync="adddialogVisible" width="40%" >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
            <el-form-item label="用户名" prop="username">
            <el-input  autocomplete="off" v-model="addForm.username" type='text' v-bind:disabled="isedit"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" class="password-box" v-show="!isedit">
            <el-input  autocomplete="off" v-model="addForm.password" type='password'></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
            <el-input  autocomplete="off" v-model="addForm.email" type='email'></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
            <el-input  autocomplete="off" v-model="addForm.mobile" ></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="adddialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data: function () {
        var checkEmail = (rule, value, cb) => {
            const regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/
            if (regEmail.test(value)) {
                return cb()
            }cb(new Error('请输入合法的邮箱！'))
        }
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^0{0,1}(13[4-9]|15[7-9]|15[0-2]|18[7-8])[0-9]{8}$/
            if (regMobile.test(value)) {
                return cb()
            }
            cb(new Error('请输入合法手机号码'))
        }
        return {
            isedit: false,
            activeeditid: '',
            adddialogVisible: false,
            msg: '',
            queryinfo: {
                query: '',
                pagenum: 1,
                pagesize: 6
            },
            userlist: [],
            total: 0,
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 15, message: '用户名的长度在3-15位', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 15, message: '用户名的长度在3-15位', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            }
        }
    },
    created: function () {
        this.getuserlist()
    },
    methods: {
        handleClose (done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done()
            })
            .catch(_ => {})
        },
        getuserlist: function () {
            this.$http.get('users', {
                params: this.queryinfo
            }).then((result) => {
                this.total = result.data.data.total
                console.log(this.total)
                if (result.data.meta.status === 200) {
                    this.userlist = result.data.data.users
                    console.log(this.userlist)
                } else {
                    this.$message.error('获取用户列表失败!')
                }
            }).catch(result => {
                console.log(result)
            })
        },
        handlecurrentchange: function (newPage) {
            this.queryinfo.pagenum = newPage
            this.getuserlist()
        },
        changestatus: function (info) {
            console.log(`users/:${info.id}/state/:${info.mg_state}`)
            this.$http.put(`users/${info.id}/state/${info.mg_state}`).then(result => {
                console.log(result)
                if (result.status !== 200) {
                this.$message.error('error，更新错误！')
                info.mg_state = !info.mg_status
                }
            }
            ).catch(() => {
                this.$message.error('error，更新错误！')
                info.mg_state = !info.mg_status
            })
        },
        diaclosed: function () {
            if (this.isedit) {
                this.isedit = false
            }
            this.$refs.addFormRef.resetFields()
        },
        addUser: function () {
            if (this.isedit) {
                this.$refs.addFormRef.validate(result => {
                    this.$http.put('users/' + this.activeeditid, {
                        id: this.activeeditid,
                        email: this.addForm.email,
                        mobile: this.addForm.mobile
                    }).then(result => {
                        if (result.data.meta.status !== 200) {
                            this.$message.error('您的信息有误！')
                            this.adddialogVisible = !this.adddialogVisible
                            return 0
                        }
                        this.getuserlist()
                        this.$message.success('修改成功！')
                        console.log(result)
                    })
                })
                this.adddialogVisible = !this.adddialogVisible
                return 0
            }
            this.$refs.addFormRef.validate((result) => {
                this.adddialogVisible = false
                if (!result) {
                    return this.$message.error('添加失败，请检查您的信息是否有误！')
                }
                this.$http.post('users', this.addForm).then((result) => {
                    if (result.data.meta.msg === '用户名已存在') {
                        return this.$message.error(result.data.meta.msg)
                    }
                    if (result.data.meta.status !== 201) {
                        return this.$message.error('系统异常，请稍后重试！')
                    }
                    this.getuserlist()
                    console.log(result)
                }).catch(error => {
                    console.log(error)
                })
            })
        },
        edituser: function (userinfo) {
            this.isedit = true
            console.log(userinfo)
            this.activeeditid = userinfo.id
            this.adddialogVisible = !this.adddialogVisible
            this.addForm.username = userinfo.username
            this.addForm.mobile = userinfo.mobile
            this.addForm.email = userinfo.email
            this.addForm.password = '******'
            this.$http.get(`users/${userinfo.id}`).then(result => {
                console.log(result)
                if (result.data.meta.status !== 200) {
                    this.$messgae.error('系统异常获，查询不到数据！')
                    this.adddialogVisible = !this.adddialogVisible
                    return 0
                }
            })
        },
        deleteuser: function (userinfo) {
            console.log(userinfo)
            this.$confirm('此操作将永久删除该用户，是否继续？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(`users/${userinfo.id}`).then(
                    (result) => {
                        if (result.data.meta.status !== 200) {
                            this.$message.error('删除失败,请稍后重试！')
                            return 0
                        }
                        this.$message({
                            type: 'success',
                            message: '删除成功！'
                        }
                        )
                        this.getuserlist()
                    }
                )
            }).catch(() => {
                this.$message.error('删除失败,您已经取消！')
            })
        }
     }
}
</script>

<style lang="less" scoped>
 .el-breadcrumb{
     height: 43px;
     line-height: 43px;
     background-color: rgb(233, 238, 243);
     position:absolute;
     top: -43px;
     margin-left: 0;
     left: 0;
     padding-left: 25px;
     padding-right: 25px;
    //  transform: translateY(-30px);
    //  z-index: 999;
    .el-breadcrumb__separator {
    margin: 0 9px;
    font-weight: 700;
    color: #536da1!important;
    }
 }
 .el-table{
        margin-top: 50px;
        margin-bottom: 55px;
    }
 .el-pagination{
     margin: 50px auto;
 }
 .el-dialog .el-form-item{
    //  display: flex;
     margin: auto;
     margin-bottom: 15px;
 }
 .el-dialog .el-form{
 }
</style>
